<?php
/**
 * 小程序轮播图API
 * 处理轮播图的查询和管理
 */

require_once 'base.php';

class CarouselAPI extends MiniappBase {
    
    /**
     * 获取轮播图列表
     */
    public function getCarousels() {
        $pagination = $this->paginate(
            $_GET['page'] ?? 1, 
            $_GET['limit'] ?? 20
        );
        
        $status = $_GET['status'] ?? 'active';
        
        try {
            // 获取轮播图列表
            $sql = "SELECT id, title, image_url, link_type, link_value, sort, status, 
                           view_count, created_at, updated_at 
                    FROM carousels 
                    WHERE status = ? 
                    ORDER BY sort ASC, id DESC 
                    LIMIT {$pagination['limit']} OFFSET {$pagination['offset']}";
            
            $carousels = $this->db->fetchAll($sql, [$status]);
            
            // 获取总数
            $countSql = "SELECT COUNT(*) as total FROM carousels WHERE status = ?";
            $total = $this->db->fetchOne($countSql, [$status])['total'];
            
            // 格式化数据
            foreach ($carousels as &$carousel) {
                $carousel['created_at'] = $this->formatTime($carousel['created_at']);
                $carousel['updated_at'] = $this->formatTime($carousel['updated_at']);
                $carousel['view_count'] = intval($carousel['view_count']);
                $carousel['sort'] = intval($carousel['sort']);
            }
            
            $this->success([
                'list' => $carousels,
                'pagination' => [
                    'page' => $pagination['page'],
                    'limit' => $pagination['limit'],
                    'total' => intval($total),
                    'pages' => ceil($total / $pagination['limit'])
                ]
            ]);
            
        } catch (Exception $e) {
            $this->error('获取轮播图失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 获取轮播图详情
     */
    public function getCarousel($id) {
        if (empty($id)) {
            $this->error('缺少轮播图ID');
        }
        
        try {
            $sql = "SELECT * FROM carousels WHERE id = ?";
            $carousel = $this->db->fetchOne($sql, [$id]);
            
            if (!$carousel) {
                $this->error('轮播图不存在', 404);
            }
            
            // 更新浏览次数
            $updateSql = "UPDATE carousels SET view_count = view_count + 1 WHERE id = ?";
            $this->db->query($updateSql, [$id]);
            
            $carousel['view_count'] = intval($carousel['view_count']) + 1;
            $carousel['sort'] = intval($carousel['sort']);
            $carousel['created_at'] = $this->formatTime($carousel['created_at']);
            $carousel['updated_at'] = $this->formatTime($carousel['updated_at']);
            
            $this->success($carousel);
            
        } catch (Exception $e) {
            $this->error('获取轮播图详情失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 点击轮播图 - 记录点击统计
     */
    public function clickCarousel($id) {
        if (empty($id)) {
            $this->error('缺少轮播图ID');
        }
        
        try {
            // 验证轮播图存在
            $sql = "SELECT id, link_type, link_value FROM carousels WHERE id = ? AND status = 'active'";
            $carousel = $this->db->fetchOne($sql, [$id]);
            
            if (!$carousel) {
                $this->error('轮播图不存在或已下线', 404);
            }
            
            // 更新点击次数
            $updateSql = "UPDATE carousels SET click_count = click_count + 1 WHERE id = ?";
            $this->db->query($updateSql, [$id]);
            
            // 记录点击日志
            $logData = [
                'carousel_id' => $id,
                'user_ip' => $_SERVER['REMOTE_ADDR'] ?? 'unknown',
                'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? '',
                'clicked_at' => date('Y-m-d H:i:s')
            ];
            
            $this->db->insert('carousel_clicks', $logData);
            
            $this->success([
                'link_type' => $carousel['link_type'],
                'link_value' => $carousel['link_value']
            ], '点击记录成功');
            
        } catch (Exception $e) {
            $this->error('处理点击失败: ' . $e->getMessage());
        }
    }
}

// 处理请求
$carousel = new CarouselAPI();

$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? 'list';

if ($method === 'GET') {
    switch ($action) {
        case 'list':
            $carousel->getCarousels();
            break;
        case 'detail':
            $carousel->getCarousel($_GET['id'] ?? '');
            break;
        case 'click':
            // 兼容 GET 方式点击记录
            $carousel->clickCarousel($_GET['id'] ?? '');
            break;
        default:
            $carousel->error('无效的操作');
    }
} elseif ($method === 'POST') {
    switch ($action) {
        case 'click':
            $carousel->clickCarousel($_POST['id'] ?? $_GET['id'] ?? '');
            break;
        default:
            $carousel->error('无效的操作');
    }
} else {
    $carousel->error('不支持的请求方法');
}
?>